package com.sasken.pdb.controllers.validators
{
	import com.sasken.pdb.models.settings.ListUtil;
	
	import mx.collections.IList;
	import mx.controls.Alert;
	import mx.utils.ObjectUtil;
	import mx.validators.StringValidator;
	import mx.validators.ValidationResult;

	/**
	 *  Validates that a string can not be found from 
	 *  a list.
	 */ 
	public class UniqueStringValidator extends StringValidator
	{
		
		private var results:Array;
		private var dpToTest:IList;
		private var fieldToTest:String;
		
		private var self:Object;
		
		public function UniqueStringValidator()
		{
			super();
			fieldToTest = "";
			results = [];
		}
		
		/**
		 *  An object that is to be excluded from the dataprovider.
		 *  If not set, this property will have no effect. 
		 * 	When validator is used with a model, the model's field property
		 *  is used against checking. 
		 */ 
		public function set excludedObject(value:Object):void
		{
			self = value;
		}
		
		public function set dataProvider(value:IList):void
		{
			dpToTest = value;
		}
		
		public function set field(value:String):void
		{
			fieldToTest = value;
		}
		
		
		protected override function doValidation(value:Object):Array
		{
			// Call base class doValidation().
            results = super.doValidation(value);        
            
            // Return if there are errors.
            if (results.length > 0)
            {
           		return results;
            }   
			
			if (!dpToTest)
			{
				return [];
			}	
			
			var index:int = ListUtil.findByAttribute(dpToTest, fieldToTest, value);
			
			if (index != ListUtil.NOT_FOUND)
			{
				if (!self || dpToTest.getItemAt(index) != self)
				{
					results.push(new ValidationResult(true, null, "notUnique", 
								 "This field is not unique."));
				}
			}
			
			return results;
		}
		
	}
}